package com.ihr360.expr.operator;

import com.ihr360.expr.ExprBigDecimal;
import com.ihr360.expr.ExprDouble;
import com.ihr360.expr.ExprError;
import com.ihr360.expr.ExprException;
import com.ihr360.expr.core.AbstractMathematicalOperator;
import com.ihr360.expr.core.Expr;
import com.ihr360.expr.core.ExprType;

import java.math.BigDecimal;

/**
 * 四则运算除法
 */
public class ExprDivision extends AbstractMathematicalOperator {
    public ExprDivision(Expr lhs, Expr rhs) {
        super(ExprType.Division, lhs, rhs);
    }

    @Override
    protected Expr evaluate(double lhs, double rhs) throws ExprException {
        if (rhs == 0.) {
            return ExprError.DIV0;
        }
        //默认精确到12位精度和double保持一致
        BigDecimal result=BigDecimal.valueOf(lhs).
                divide(BigDecimal.valueOf(rhs),12,BigDecimal.ROUND_HALF_EVEN);
        return new ExprDouble(result.doubleValue());
    }

    @Override
    protected Expr evaluate(BigDecimal lhs, BigDecimal rhs) throws ExprException {
        if (rhs==null || lhs==null){
            return ExprError.NULL;
        }
        if (rhs.equals(BigDecimal.ZERO)){
            return ExprError.DIV0;
        }
        return new ExprBigDecimal(lhs.divide(rhs));
    }

    @Override
    public String toString() {
        return lhs+"/"+rhs;
    }
}